package com.jahentao.patentQuery.web.shiro.jcaptcha;

import org.springframework.web.filter.OncePerRequestFilter;

import javax.imageio.ImageIO;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * <p>用于生成验证码图片的过滤器
 * <p>专门处理获取验证码请求 jcaptcha.jpg
 *
 * @author jahentao
 * @since 1.0
 */
public class JCaptchaFilter extends OncePerRequestFilter {

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

		response.setDateHeader("Expires", 0L);
		response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		response.setHeader("Pragma", "no-cache");
		response.setContentType("image/jpeg");

		//从 cookie 中获取 id
//		String id = request.getRequestedSessionId();
//		if(StringUtils.isBlank(id)){
		String id = request.getSession().getId();
	//	}

		// 其他设置id的尝试
//		String id = SecurityUtils.getSubject().getSession().getId().toString();

//		String id = request.getRequestedSessionId();
//		Cookie[] cookies = request.getCookies();
//		if(StringUtils.isBlank(id) && cookies==null){
//			id = SecurityUtils.getSubject().getSession(true).getId().toString();
//			response.setHeader("Set-Cookie","sid="+id+"; Path="+request.getContextPath()+"; HttpOnly");
//		}else {
//			if (cookies!=null)
//				id = cookies[0].getValue();
//		}

		//使用当前会话ID当作key获取相应的验证码图片
		BufferedImage bi = JCaptcha.captchaService.getImageChallengeForID(id);
		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(bi, "jpg", out);
		try {
			out.flush();
		} finally {
			out.close();
		}
	}

}